package com.stars.icp.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.stars.icp.constant.CommonConstant;
import com.stars.icp.dto.DomainIopVO;
import com.stars.icp.dto.IcpVO;
import com.stars.icp.utils.ObjectUtils;
import com.stars.icp.utils.R;
import okhttp3.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 获取域名备案接口
 * @Author: Stars
 * @Date: 2024/12/8 16:17
 */
public class IcpService {

    private OkHttpClient client = new OkHttpClient();

    /**
     * 获取域名备案信息
     * @param domainList 需要查询的域名
     * @param accessKey ak
     * @param secretKey sk
     * @return
     */
    public DomainIopVO fetchDomain(List<String> domainList,String accessKey,String secretKey) throws IOException {
        if (domainList == null || domainList.isEmpty()) {
            throw new IllegalArgumentException("Domain list is null or empty.");
        }
        JSONObject json = new JSONObject();
        json.put("domainList", domainList);
        json.put("callbackUrl", "https://");
        json.put("accessKey", accessKey);
        json.put("secretKey", secretKey);
        RequestBody requestBody = RequestBody.create(JSON.toJSONString(json), MediaType.parse("application/json"));
        Request request = new Request.Builder().url(CommonConstant.HOST).post(requestBody).build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            assert response.body() != null;
            String responseData = response.body().string();
            R r = JSON.parseObject(responseData, R.class);
            if (r.getCode() == R.SUCCESS) {
                if (!ObjectUtils.isEmpty(r.getData())) {
                    return JSON.parseObject(r.getData().toString(), DomainIopVO.class);
                }
            } else {
                throw new IOException(r.getMsg());
            }
        } else {
            System.out.println("Error: " + response.code());
        }
        return null;
    }

    public static void main(String[] args) throws IOException {
        List<String> domainList = new ArrayList<>();
        domainList.add("www.baidu.com");
        domainList.add("baidu.com");
        domainList.add("jd.com");
        domainList.add("web.huibox.net.jd.com");
        domainList.add("asdf16er4g84ef64sfasd.jd.com");
        domainList.add("sdfasdf65er4f6ewf64erfs6df4a5sd.jd.com");
        domainList.add("www.google.com");
        domainList.add("asdfas.asdf.ergferw.huawei.net");
        domainList.add("asdfas.asdf.ergferw.chlao.net");
        DomainIopVO domainIopVO = new IcpService().fetchDomain(domainList, null, null);
        List<IcpVO> icpList = domainIopVO.getIcpList();
        List<String> noList = domainIopVO.getNoList();

        System.out.println(icpList);

    }
}
